//
//  CitySelectorViewController.swift
//  HealthMonitoring
//
//  Created by 珠海正杰 on 2018/8/7.
//  Copyright © 2018年 YTYanK. All rights reserved.
//



import UIKit
import WebViewJavascriptBridge

class CitySelectorViewController: HMViewController,UIWebViewDelegate {
    
    var bridge: WebViewJavascriptBridge? = nil
    let webView = UIWebView()
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    override func setupView() {
      
        
        webView.frame = view.bounds
        view.addSubview(webView)
        
        let htmlPath = Bundle.main.path(forResource: "ts", ofType: "html")
        let apphtml = try? NSString.init(contentsOfFile: htmlPath!, encoding: String.Encoding.utf8.rawValue)  //NSString(contentsOfFile: htmlPath!, encoding: Encoding.utf8)
        let baseURL = NSURL.fileURL(withPath: htmlPath!)
        webView.loadHTMLString(apphtml as! String, baseURL: baseURL)
        
        //开启日志
        WebViewJavascriptBridge.enableLogging()
        // 给webview建立JS与IOS的沟通桥梁
        self.bridge = WebViewJavascriptBridge.init(forWebView: webView)
        self.bridge?.setWebViewDelegate(self)
        
        /*
            JS主动调用OjbC的方法  , IOS端注册给JS调用的
         */
        // 这是JS会调用getUserIdFromObjC方法
        // JS需要回调，当然JS也可以传参数过来。data就是JS所传的参数，不一定需要传
        // OC端通过responseCallback回调JS端，JS就可以得到所需要的数据
        
        self.bridge?.registerHandler("getUserIdFromObjC", handler: { (_data, _back) in
              print("---registerHandler1-----\(String(describing: _data))")
            if (_back != nil) {  // 反馈给JS
                _back!(["userId": "123456"])
            }
            
        })

        // 调用时显示
        self.bridge?.registerHandler("getBlogNameFromObjC", handler: { (_data, _back) in
            print("---registerHandler2-----\(String(describing: _data))")
        })
        
        // 为什么这个先加载？getUserInfos
//        self.bridge?.callHandler("getUserInfos", data: ["name":"哥哥"])
        self.bridge?.callHandler("getUserInfos", data: ["xxxname":"哥哥"], responseCallback: { (_data) in
               print("--callHandler------\(String(describing: _data))")
        })
        
    }
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        print("开始加载web内容")
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        print("web内容加载结束")
    }
    func renderButtons(webView:UIWebView) -> Void {
     
    }
    
    func onOpenBlogArticle(sender: Any) -> Void {
        print("--------openWeb")
        self.bridge?.callHandler("openWebviewBridgeArticle", data: nil)
    }
    
}
